
import reqwest from 'reqwest';
import { message } from 'antd';
import Request from '../../utils/request.js';
import API from '../../../../config/api';
import * as types from './actionTypes';
import { setFetching,setLoading } from '../common/actions';

export function delRow(id) {
    return (dispatch) => {
        dispatch(setLoading(true))
        reqwest(Request.getOptions(
            "delete",
            API.role +"/"+ id,
            null,
            true
        )).then( response => {
            message.success(response.message);
            dispatch(getRows({}))
        }).fail(function (err) {
            Request.handleError(err);
        }).always((resp) =>{
            dispatch(setLoading(false));
        })
    }
}

export function saveRow(row,cb) {
    return (dispatch,getState) => {
        dispatch(setLoading(true))
        let {key} = getState().role.row;
        reqwest(Request.getOptions(
            key ? "put" : "post",
            API.role + ( key ? "/" + key : ""),
            row,
            true
        )).then( response => {
            //console.log(response);
            message.success("保存成功");
            dispatch(_setRow({}))
            dispatch(getRows({}))
            cb();
        }).fail(function (err) {
            Request.handleError(err);
        }).always((resp) =>{
            dispatch(setLoading(false));
        })
    }
}
export function _setRows(rows){
    return {type:types.SET_ROWS,rows}
}
export function _setRow(row){
    return {type:types.SET_ROW,row}
}
export function getRow(id,cb) {
    return dispatch =>{
        dispatch(setLoading(true))
        reqwest(Request.getOptions(
            "get",
            API.role+"/"+id,
            null,
            true
        )).then( response => {
            dispatch(_setRow(response));
            cb()
        }).fail(function (err) {
            Request.handleError(err);
        }).always((resp) =>{
            dispatch(setLoading(false))
        })
    }
}
export function getRows(data){
    return (dispatch,getState) => {
        //dispatch(setFetching("FETCHING_ROWS",true))
        reqwest(Request.getOptions(
            "post",
            API.roles,
            data,
            true
        )).then( response => {
            dispatch(_setRows(response))
        }).fail(function (err) {
            Request.handleError(err);
        }).always((resp) =>{
            //dispatch(setFetching("FETCHING_ROWS",false))
        })
    }
}